#!/bin/bash

# 定义监测间隔（秒）
INTERVAL=1

# 定义结果文件名
FILESTAMP=$(date +"%Y%m%d%H%M%S%N")
RESULT_FILE="cpu_mem_monitor_${FILESTAMP}.txt"

# 表头写入文件
echo "timestamp,cpu_usage,mem_usage" > ${RESULT_FILE}

while true; do
    # 获取当前时间戳
    TIMESTAMP=$(date +"%Y-%m-%d %H:%M:%S")

    # 获取CPU使用率
    CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}')

    # 获取内存使用率
    MEM_USAGE=$(free -m | awk 'NR==2{printf "%.2f", $3*100/$2 }')

    # 将结果写入文件
    echo "${TIMESTAMP},${CPU_USAGE},${MEM_USAGE}" >> ${RESULT_FILE}

    # 等待一段时间后再次监测
    sleep ${INTERVAL}
done